/**
 * Malsha 2014/09/23
 */

PlacementSheet = new Object();

var plasementsheetid = null;
var customerData = null;
var customer_accounts = Ext.create('Ext.data.Store', {
	fields : [ 'accountNo', 'branch', 'nameOfBank', 'customer', 'bankid' ]
});

var fund_store = Ext.create('Ext.data.Store', {
	fields : [ 'id', 'name', 'code', 'unitValue' ]
});
var money_from_store = Ext.create('Ext.data.Store', {
	fields : [ 'customer_id', 'customer_name', 'customer_type', 'comingFromBank', 'bank_id', 'amount', 'fund', 'date', 'moneyInOut', 'payReceNo' ]
});

var money_to_store = Ext.create('Ext.data.Store', {
	fields : [ 'customer_id', 'customer_name', 'customer_type', 'comingFromBank', 'bank_id', 'amount', 'fund', 'date', 'moneyInOut', 'payReceNo' ]
});

PlacementSheet.getComingInGird = function() {
	var comingIngrid = null;
	comingIngrid = Ext.create('Ext.grid.Panel', {
		title : 'MONEY COMING IN FROM',
		id : 'comingIn_grid',
		store : money_from_store,
		height : 250,
		features : [ {
			ftype : 'summary'
		} ],
		columns : [ {
			header : 'Direct Credit O/A',
			dataIndex : 'customer_name',
			width : 150
		}, {
			header : 'Transaction Volume <br> LKR Amount',
			dataIndex : 'amount',
			xtype : 'numbercolumn',
			format : '0,000.0000',
			align : 'right',
			width : 200,
			summaryType : 'sum',
			summaryRenderer : function(value, summaryData, dataIndex) {
				var val = Ext.util.Format.number(value, '0,000.0000');
				return Ext.String.format('<B>Total</B>\t{0}', val);
			},
		}, {
			header : 'Financial Institution <br> Money Coming In From',
			dataIndex : 'comingFromBank',
			width : 125,
			flex : 1
		}, {
			xtype : 'actioncolumn',
			width : 50,
			align : 'center',
			items : [ {
				icon : 'images/Delete.jpg',
				tooltip : 'Delete',
				handler : function(grid, rowIndex, colIndex) {
					var rec = grid.getStore().getAt(rowIndex);
					if (rec) {
						money_from_store.remove(rec);
					}
				}
			} ]
		} ]
	});
	return comingIngrid;
};

PlacementSheet.GoingOutGrid = function() {
	var goingOutgrid = null;
	goingOutgrid = Ext.create('Ext.grid.Panel', {
		title : 'MONEY GOING OUT TO',
		id : 'goingout_grid',
		store : money_to_store,
		height : 250,
		features : [ {
			ftype : 'summary'
		} ],
		columns : [ {
			header : 'Direct Debit O/A',
			dataIndex : 'customer_name',
			width : 150
		}, {
			header : 'Transaction Volume <br> LKR Amount',
			dataIndex : 'amount',
			xtype : 'numbercolumn',
			format : '0,000.0000',
			align : 'right',
			flex : 1,
			summaryType : 'sum',
			summaryRenderer : function(value, summaryData, dataIndex) {
				var val = Ext.util.Format.number(value, '0,000.0000');
				return Ext.String.format('<B>Total</B>\t{0}', val);
			},
		}, {
			header : 'Financial Institution <br> Money Going Out To',
			dataIndex : 'comingFromBank',
			width : 125,
			flex : 1
		}, {
			xtype : 'actioncolumn',
			width : 50,
			align : 'center',
			items : [ {
				icon : 'images/Delete.jpg',
				tooltip : 'Delete',
				handler : function(grid, rowIndex, colIndex) {
					var rec = grid.getStore().getAt(rowIndex);
					if (rec) {
						money_to_store.remove(rec);
					}
				}
			} ]
		} ]
	});
	return goingOutgrid;
};

PlacementSheet.getCenterPanel = function() {

	var comingin = PlacementSheet.getComingInGird();
	var goingout = PlacementSheet.GoingOutGrid();
	money_to_store.removeAll();
	money_from_store.removeAll();

	formpanel = Ext.create('Ext.form.Panel', {
		title : 'Placement Sheet',
		bodyPadding : 20,
		autoScroll : true,
		frame : true,
		id : 'palcementsheet_form',
		defaults : {
			labelWidth : 110,
			anchor : '65%',
		},
		items : [ {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ {
				xtype : 'datefield',
				fieldLabel : 'Date',
				labelWidth : 50,
				width : 225,
				id : 'date',
				name : 'date',
				value : new Date(),
				format : 'd/m/Y',
				submitFormat : 'd/m/Y',
				padding : '0 15 0 0',
			}, {
				xtype : 'combo',
				fieldLabel : 'Fund<span style="color:red">*</span>',
				flex : 1,
				labelWidth : 90,
				anchor : '70%',
				id : 'fund',
				padding : '0 10 0 0',
				store : fund_store,
				valueField : 'id',
				displayField : 'code',
				emptyText : 'Select a Fund...',
				isLoaded : false,
				allowBlank : false,
				msgTarget : 'under',
				name : 'fund',
				queryMode : 'local',
				tpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '<div class="x-boundlist-item">{code} - {name}</div>', '</tpl>'),
				displayTpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '{code} - {name}', '</tpl>'),
				listeners : {
					expand : function(combo, opt) {
						if (!combo.isLoaded) {
							Ext.Ajax.request({
								url : 'getFundVsUnitValue.action',
								success : function(response) {
									var obj = Ext.decode(response.responseText);
									combo.getStore().loadRawData(obj.fundDtos);
									combo.isLoaded = true;
								}
							});
						}
					}
				},
				listConfig : {
					listeners : {
						itemclick : function(list, record) {

							var date = Ext.Date.format(Ext.getCmp('date').getValue(), 'd/m/Y');
							if (record.get('code') != null) {
								// Ext.Ajax.request({
								// url : 'getPlacementbyFund.action',
								// params : {
								// "fundid" : record.get('id'),
								// "seldate" : date,
								// },
								// success : function(response) {}
								// });
								// var obj = Ext.decode(response.responseText);
								// if (obj.placementSheetDtos.length > 0) {}
								// else {
								// Ext.getCmp('transaction_details').enable();
								// Ext.getCmp('save').enable();
								// Ext.getCmp('confirm').enable();
								// Ext.getCmp('reject').enable();
								// Ext.getCmp('print').disable();
								// money_to_store.removeAll();
								// money_from_store.removeAll();
								// }
								var myMask = new Ext.LoadMask(formpanel, {
									msg : "Loading..."
								});
								myMask.show();
								Ext.Ajax.request({
									url : 'getPlacementSheetbyFund.action',
									params : {
										"fundid" : record.get('id'),
										"date" : date,
									},
									success : function(response) {
										var obj = Ext.decode(response.responseText);
										PlacementSheet.loadRecord(obj.placementRecordDtos);
										myMask.hide();
									}
								});
								// Ext.each(obj.placementSheetDtos,
								// function(record, index) {
								// if (record.status == "INITIAL") {
								// Ext.getCmp('transaction_details').enable();
								// Ext.getCmp('save').enable();
								// Ext.getCmp('confirm').enable();
								// Ext.getCmp('reject').enable();
								// Ext.getCmp('print').disable();
								// } else if (record.status == "CONFIRM") {
								// Ext.getCmp('transaction_details').disable();
								// Ext.getCmp('save').disable();
								// Ext.getCmp('confirm').disable();
								// Ext.getCmp('reject').disable();
								// Ext.getCmp('print').enable();
								// } else {
								// Ext.getCmp('transaction_details').disable();
								// Ext.getCmp('save').disable();
								// Ext.getCmp('confirm').disable();
								// Ext.getCmp('reject').disable();
								// Ext.getCmp('print').disable();
								// }
								// });
								//							
							}
						}
					}
				}
			} ]
		}, {
			xtype : 'form',
			bodyBorder : false,
			frame : true,
			border : false,
			id : 'transaction_details',
			items : [ {
				xtype : 'triggerfield',
				emptyText : 'Search Customer',
				triggerCls : 'x-form-search-trigger',
				fieldLabel : 'Customer',
				name : 'customer',
				id : 'customer',
				anchor : '70%',
				onTriggerClick : function() {
					var window = null;
					if (!window) {
						window = Ext.create('Ext.window.Window', {
							title : 'Customer',
							height : 330,
							frame : true,
							width : 500,
							constrain : true,
							resizable : false,
							modal : true,
							layout : {
								type : 'accordion',
								animate : true,
								hideCollapseTool : true,
							},
							items : [ {
								xtype : 'form',
								title : 'Search Criteria',
								bodyPadding : 20,
								autoScroll : true,
								frame : true,
								items : [ {
									xtype : 'fieldcontainer',
									fieldLabel : 'Customer Type',
									defaultType : 'radiofield',
									layout : 'hbox',
									items : [ {
										boxLabel : 'Customer',
										name : 'customerType',
										padding : '0 5 0 0',
										checked : true,
										inputValue : 'CUS',
									}, {
										boxLabel : 'Issuer',
										name : 'customerType',
										padding : '0 5 0 0',
										inputValue : 'ISU',
									}, {
										boxLabel : 'Other',
										name : 'customerType',
										inputValue : 'O',
									} ]
								}, {
									xtype : 'textfield',
									fieldLabel : 'Code',
									name : 'customerCode',
								}, {
									xtype : 'textfield',
									fieldLabel : 'Name',
									name : 'customerName',
								} ],
								buttonAlign : 'center',
								buttons : [ {
									text : 'Reset',
									handler : function() {
										this.up('form').getForm().reset();
									}
								}, {
									text : 'Search',
									handler : function() {
										var form = this.up('form').getForm();
										if (form.isValid()) {
											form.url = 'getCustomerByType.action';
											form.submit({
												success : function(form, action, response) {
													gidplen = Ext.getCmp('search_result');
													var obj = Ext.decode(action.response.responseText);
													gidplen.getStore().removeAll();
													gidplen.getStore().loadRawData(obj.allCustomers);
													gidplen.expand();
												},
												failure : function(form, action) {
													Ext.Msg.alert('Failed', action.result.resulteMsg);
												}
											});
										}
									}
								} ]
							}, new Ext.grid.Panel({
								title : 'Search Result',
								id : 'search_result',
								store : Ext.create('Ext.data.Store', {
									fields : [ 'customerId', 'customerType', 'customerCode', 'customerName' ]
								}),
								columns : [ {
									text : 'Customer Code',
									dataIndex : 'customerCode',
									flex : 1
								}, {
									text : 'Name',
									dataIndex : 'customerName',
									flex : 1.4
								} ],
								listeners : {
									itemdblclick : function(dv, record, item, index, e) {
										var data = record.data;
										PlacementSheet.setCustomer(data, record);
										window.close();
									}
								}
							}) ]
						});
					}
					if (window.isVisible()) {
						window.hide();
					} else {
						window.show();
					}
				}
			}, {
				fieldLabel : 'Bank Account',
				xtype : 'combo',
				store : customer_accounts,
				valueField : 'bankid',
				displayField : 'accountNo',
				queryMode : 'local',
				id : 'bank_account',
				msgTarget : 'under',
				name : 'bankAccount',
				anchor : '70%',
				tpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '<div class="x-boundlist-item">{accountNo} - {nameOfBank}</div>', '</tpl>'),
				displayTpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '{accountNo} - {nameOfBank}', '</tpl>'),
				listeners : {
					change : function(combo, record, index) {
						if (combo.getValue() == "" || combo.getValue() == "&nbsp;" || combo.getValue == 0)
							combo.setValue(null);
					}
				}
			}, {
				xtype : 'fieldcontainer',
				fieldLabel : 'Money Coming',
				defaultType : 'radiofield',
				layout : 'hbox',
				items : [ {
					boxLabel : 'IN',
					name : 'inout',
					id : 'moneyin',
					padding : '0 5 0 0',
					checked : true,
					inputValue : 'IN',
				}, {
					boxLabel : 'OUT',
					name : 'inout',
					id : 'moneyout',
					padding : '0 5 0 0',
					inputValue : 'OUT',
				} ]
			}, {
				xtype : 'textfield',
				fieldLabel : 'Amount <span style="color:red">*</span>',
				minValue : 0,
				id : 'amount',
				name : 'amount',
				readOnly : false,
				msgTarget : 'under',
				anchor : '45%',
				fieldStyle : "text-align:right;",
				maskRe : /[\d\,.]/,
				listeners : {
					blur : function() {
						var val = this.value.replace(/,/g, '');
						this.setRawValue(Ext.util.Format.number(val, '0,000.0000'));
					},
					render : function() {
						this.setRawValue(Ext.util.Format.number(this.value, '0,000.0000'));
					}
				}
			} ],
			buttonAlign : 'center',
			buttons : [ {
				xtype : 'button',
				text : 'Add',
				listeners : {
					click : function() {
						var form = this.up('form').getForm();
						// if (form.isValid()) {
						console.log(Ext.getCmp('bank_account').getValue());
						if (Ext.getCmp('amount').getValue() != null && Ext.getCmp('amount').getValue() != "" && Ext.getCmp('bank_account').getValue() != null) {

							var recordIndex_from = money_from_store.findBy(function(record, id) {
								if (record.get('customer_id') === customerData.customerId) {
									return true;
								}
								return false;
							});

							var recordIndex_to = money_to_store.findBy(function(record, id) {
								if (record.get('customer_id') === customerData.customerId) {
									return true;
								}
								return false;
							});

							if (recordIndex_from != -1 || recordIndex_to != -1) {
								Ext.Msg.alert('Error', "Duplicate recode fund");
							} else {
								if (Ext.getCmp('moneyin').getValue()) {
									money_from_store.add({
										customer_id : customerData.customerId,
										customer_name : Ext.getCmp('customer').getValue(),
										customer_type : customerData.customerType,
										comingFromBank : Ext.getCmp('bank_account').getRawValue(),
										bank_id : Ext.getCmp('bank_account').getValue(),
										amount : Ext.getCmp('amount').getValue().replace(/,/g, ''),
									});
									customerData = null;
									form.reset();
									Ext.getCmp('bank_account').clearValue();
									customer_accounts.removeAll();
								} else {
									money_to_store.add({
										customer_id : customerData.customerId,
										customer_name : Ext.getCmp('customer').getValue(),
										customer_type : customerData.customerType,
										comingFromBank : Ext.getCmp('bank_account').getRawValue(),
										bank_id : Ext.getCmp('bank_account').getValue(),
										amount : Ext.getCmp('amount').getValue().replace(/,/g, ''),
									});
									customerData = null;
									form.reset();
									Ext.getCmp('bank_account').clearValue();
									customer_accounts.removeAll();
								}
							}
							// }
							// else {
							// Ext.Msg.alert('Failed', "Form is invalid");
							// }
						}
					}
				}
			}, {
				xtype : 'button',
				text : 'Reset',
				listeners : {
					click : function() {
						this.up('form').getForm().reset();
					}
				}
			} ]
		}, comingin, goingout ],
		buttonAlign : 'center',
		buttons : [ {
			text : 'Cancel',
			handler : function() {
				App.Core.removeScreen();
			}
		}, {
			text : 'Reset',
			handler : function() {
				this.up('form').getForm().reset();
				money_to_store.removeAll();
				money_from_store.removeAll();
				Ext.getCmp('transaction_details').enable();
				Ext.getCmp('save').enable();
				Ext.getCmp('confirm').enable();
				Ext.getCmp('reject').enable();
				Ext.getCmp('print').disable();
			}
		}, {
			text : 'Save',
			id : 'save',
			handler : function() {
				var form = Ext.getCmp('palcementsheet_form').getForm();
				var transactions = [];
				money_to_store.each(function(record) {
					if (record.get('amount') > 0) {
						var obj = {
							"customer_type" : record.get('customer_type'),
							"customer_id" : record.get('customer_id'),
							"customer_name" : record.get('customer_name'),
							"comingFromBank" : record.get('comingFromBank'),
							"bank_id" : record.get('bank_id'),
							"amount" : record.get('amount'),
							"moneyInOut" : "OUT",
							"payReceNo" : record.get('payReceNo')
						};
						transactions.push(obj);
					}
				});
				money_from_store.each(function(record) {
					if (record.get('amount') > 0) {
						var obj = {
							"customer_type" : record.get('customer_type'),
							"customer_id" : record.get('customer_id'),
							"customer_name" : record.get('customer_name'),
							"comingFromBank" : record.get('comingFromBank'),
							"bank_id" : record.get('bank_id'),
							"amount" : record.get('amount'),
							"moneyInOut" : "IN",
							"payReceNo" : record.get('payReceNo')
						};
						transactions.push(obj);
					}
				});

				if (plasementsheetid == null) {
					form.url = 'addplacementsheet.action';
					form.submit({
						params : {
							"transactions" : Ext.encode(transactions),
						},
						success : function(form, action) {
							form.reset();
							plasementsheetid = null;
							money_to_store.removeAll();
							money_from_store.removeAll();
							Ext.Msg.alert('Success', 'Saved Successfully');
						},
						failure : function(form, action) {
							Ext.Msg.alert('Failed', action.result.resulteMsg);
						}
					});
				} else {
					form.url = 'updateplacementsheet.action';
					form.submit({
						params : {
							"transactions" : Ext.encode(transactions),
							"plasementsheetid" : plasementsheetid
						},
						success : function(form, action) {
							form.reset();
							plasementsheetid = null;
							money_to_store.removeAll();
							money_from_store.removeAll();
							Ext.Msg.alert('Success', 'Update Successfully');
						},
						failure : function(form, action) {
							Ext.Msg.alert('Failed', action.result.resulteMsg);
						}
					});
				}
			}
		}, {
			text : 'Confirm',
			id : 'confirm',
			disabled : false,
			handler : function() {
				var form = Ext.getCmp('palcementsheet_form').getForm();
				Ext.Ajax.request({
					url : 'confirmPlacement.action',
					params : {
						"plasementsheetid" : plasementsheetid,
					},
					success : function(response) {
						form.reset();
						plasementsheetid = null;
						money_to_store.removeAll();
						money_from_store.removeAll();
						Ext.Msg.alert('Success', 'Confirm Successfully');
					},
					failure : function(response) {
						Ext.Msg.alert('Failed', "There is some error returned from the server.");
					}
				});
			}
		}, {
			text : 'Reject',
			id : 'reject',
			disabled : false,
			handler : function() {
				var form = Ext.getCmp('palcementsheet_form').getForm();
				Ext.Ajax.request({
					url : 'rejectPlacement.action',
					params : {
						"plasementsheetid" : plasementsheetid,
					},
					success : function(response) {
						form.reset();
						plasementsheetid = null;
						money_to_store.removeAll();
						money_from_store.removeAll();
						Ext.Msg.alert('Success', 'Reject Successfully');
					},
					failure : function(response) {
						Ext.Msg.alert('Failed', "There is some error returned from the server.");
					}
				});
			}
		}, {
			text : 'Print',
			id : 'print',
			disabled : true,
			handler : function() {
				var param = {
					'PlacementSheetId' : plasementsheetid
				};
				Report.OpenWindowWithPost('ReportServlet/placementsheet', "width=1000, height=600, left=100, top=100,resizable=yes, scrollbars=yes", "NewFile", param);

			}
		} ],
	});

	return formpanel;
};

PlacementSheet.loadRecord = function(records) {

	money_to_store.removeAll();
	money_from_store.removeAll();

	Ext.each(records, function(record, index) {
		if (record.moneyInOut == "OUT") {
			money_to_store.add(record);
		} else {
			money_from_store.add(record);
		}
		plasementsheetid = record.placementSheet;
	});
};

PlacementSheet.setCustomer = function(data, record) {

	Ext.getCmp('customer').setValue(data.customerName);
	customerData = data;
	Ext.Ajax.request({
		url : 'getBankAccountByCustomerType.action',
		params : {
			"customer_id" : data.customerId,
			"customerType" : data.customerType,
		},
		success : function(response) {
			var obj = Ext.decode(response.responseText);
			Ext.getCmp('bank_account').clearValue();
			customer_accounts.removeAll();
			customer_accounts.loadRawData(obj.accountDtos);
		}
	});
};